package com.java.es.pojo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jiangli
 * @date 2019/11/18 22:23
 * lock版
 */
public class ThreadNotifyDemo2 {

	public static void main(String[] args) {
		Res2 res = new Res2();
		Input2 input = new Input2(res);
		Output2 output = new Output2(res);
		input.start();
		output.start();
	}
}

class Input2 extends Thread {
	private Res2 res;

	public Input2(Res2 res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {

			try {
				res.lock.lock();
				if (res.flag) {
					try {
						res.condition.await();
					} catch (InterruptedException e) {
					}
				}
				if (count == 0) {
					res.name = "杨过";
					res.sex = "男";
				} else {
					res.name = "小龙女";
					res.sex = "女";
				}
				count = (count + 1) % 2;
				res.flag = true;
				res.condition.signal();
			} finally {
				//finally里面只释放锁,不做其他操作
				res.lock.unlock();
			}
		}

	}
}

class Output2 extends Thread {
	private Res2 res;

	public Output2(Res2 res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {

			try {
				res.lock.lock();
				if (!res.flag) {
					try {
						//线程等待
						res.condition.await();
					} catch (InterruptedException e) {
					}
				}
				System.out.println("名字:" + res.name + ", 性别:" + res.sex);
				//重置标识
				res.flag = false;
				//唤醒另一线程
				res.condition.signal();
			} finally {
				res.lock.unlock();
			}
		}
	}
}

class Res2 {
	public String name;
	public String sex;
	// flag false out线程未读取值
	public boolean flag = false;
	Lock lock = new ReentrantLock();
	Condition condition = lock.newCondition();


}